package cn.melonlib.cores.identification.comp.messenger;

import cn.hutool.core.bean.BeanUtil;
import cn.melonlib.cores.commons.comp.utils.AdvancedStringUtils;
import cn.melonlib.cores.commons.model.entity.IEntity;
import cn.melonlib.cores.commons.model.entity.IRecordEntity;
import cn.melonlib.cores.commons.model.entity.RecordEntity;
import cn.melonlib.cores.commons.model.entity.TenantEntity;
import cn.melonlib.cores.identification.model.entity.Identification;
import cn.melonlib.cores.identification.model.entity.Organization;
import cn.melonlib.cores.jpa.model.bean.collections.JsonMap;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;

@Service
public class MessengerUtils extends ApplicationObjectSupport {

    @Resource
    @Lazy
    private IdentificationMessenger identificationMessenger;

    @Resource
    @Lazy
    private OrganizationManager<String> organizationManager;

    @Resource
    private ObjectMapper jsonMapper;

    private final ThreadLocal<String> tenant=new ThreadLocal<>();

    public void setMessengers(IEntity<? extends Serializable> entity) throws Exception {
        Identification identification = identificationMessenger.getIdentification();
        Organization organization = identificationMessenger.getOrganization();
        String idenId= AdvancedStringUtils.defaultIfBlank(BeanUtil.getProperty(identification,"openid"),
                ()->BeanUtil.getProperty(identification,"account"),
                ()->BeanUtil.getProperty(identification,"id"),()->""
                );
        String idenCode=AdvancedStringUtils.defaultIfBlank(
                BeanUtil.getProperty(identification,"username"),
                ()->BeanUtil.getProperty(identification,"loginName"),
                ()->BeanUtil.getProperty(identification,"usercode"),
                ()->BeanUtil.getProperty(identification,"userCode"),
                ()->BeanUtil.getProperty(identification,"code"),
                ()->BeanUtil.getProperty(identification,"account"),()->""
        ) ;
        String idenName= StringUtils.defaultIfBlank(BeanUtil.getProperty(identification,"name"),idenCode);
        String orgId=BeanUtil.getProperty(organization,"id");
        String orgCode=organizationManager.getCode();
        String orgName=StringUtils.defaultIfBlank(BeanUtil.getProperty(organization,"name"),orgCode);

        if (ObjectUtils.isEmpty(entity.getId())) {
            if (entity instanceof TenantEntity) {
                ((TenantEntity) entity).setTenantId(orgId);
                ((TenantEntity) entity).setTenantCode(orgCode);
                ((TenantEntity) entity).setTenantName(orgName);
//                ((TenantEntity) entity).setTenant(jsonMapper.writeValueAsString(identificationMessenger.getOrganization()));
            }
        }
        if (entity instanceof IRecordEntity) {
            if (ObjectUtils.isEmpty(entity.getId())) {
//                ((IRecordEntity) entity).setCreator(jsonMapper.writeValueAsString(identificationMessenger.getIdentification()));
                ((IRecordEntity) entity).setCreatorId(idenId);
                ((IRecordEntity) entity).setCreatorCode(idenCode);
                ((IRecordEntity) entity).setCreatorName(idenName);
            } else {
                ((IRecordEntity) entity).setLastModifiedDateTime(System.currentTimeMillis());
            }

        }
    }

    public JsonMap<JsonMap<Object>> filterTenant(JsonMap<JsonMap<Object>> filter) throws Exception {
        Organization organization= identificationMessenger.getOrganization();
        return filter
                .append("tenantCode",JsonMap.createMap().append("eq",organizationManager.getCode()))
                ;
    }

    public JsonMap<JsonMap<Object>> filterRecord(JsonMap<JsonMap<Object>> filter) {
        Identification identification=identificationMessenger.getIdentification();
        return filter.append("creatorId", JsonMap.createMap().append("eq", BeanUtil.getProperty(identification,"openid")))
                .append("creatorCode",JsonMap.createMap().append("eq",BeanUtil.getProperty(identification,"account")));
    }

    public void transMessengers(IEntity<? extends Serializable> source,IEntity<? extends Serializable> target) throws Exception{
        if(ObjectUtils.isEmpty(target.getId())) {
            if (source instanceof TenantEntity && target instanceof TenantEntity) {
                tenant.set(((TenantEntity) source).getTenantId());
                ((TenantEntity) target).setTenantId(((TenantEntity) source).getTenantId());
            }
        }
        if(target instanceof RecordEntity &&source instanceof TenantEntity){
            tenant.set(((TenantEntity) source).getTenantId());
            if(ObjectUtils.isEmpty(target.getId())) {
                ((RecordEntity) target).setCreatorId(BeanUtil.getProperty(source,"creatorId"));
            }else{
                ((RecordEntity) target).setLastModifiedDateTime(System.currentTimeMillis());
            }
        }
    }

    public void setTenant(String tenantId){
        this.tenant.set(tenantId);
    }
    public String getTenant(){
        if(StringUtils.isBlank(this.tenant.get())){
            try {
                this.tenant.set(organizationManager.getCode());
            }catch (Exception e){
                return null;
            }
        }
        return this.tenant.get();
    }
}
